// 基本信息
import { getDeptList } from "@/api/modules/dept";
import { getNotifyTemplateList } from "@/api/modules/notification";
import DialogBox from "@/components/DialogBox";
import UserSelectDialog from "./userSelectDialog.vue";
import DeptTree from "@/components/Sansan/DeptTree";
import { ElForm, ElMessage } from "element-plus";
import { defineComponent, PropType } from "vue";
import "./mould-detail.scss";
import { getUserList } from "@/api/modules/user";
import SelectDeptList from "@/components/Sansan/SelectDeptList";
interface DeviceForm {
	[key: string]: any;
}
export default defineComponent({
	props: {
		detail: {
			type: Object as PropType<DeviceForm>,
			default() {
				return {};
			}
		}
	},
	emits: ["submit"],
	setup(props, { emit, attrs }) {
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			name: [{ required: true, message: "请输入模版名称", trigger: "change" }],
			templateId: [{ required: true, message: "请选择通知模板", trigger: "change" }],
			deptId: [{ required: true, message: "请选择分组", trigger: "change" }]
		});
		const validData = () => {
			formRef.value?.validate(valid => {
				if (valid) {
					if (props.detail.sendTargetType == "1") {
						props.detail.sendTarget = assignGroup.value.map((item: any) => item.id).toString();
					} else if (props.detail.sendTargetType == "3") {
						props.detail.sendTarget = userList.value.map((item: any) => item.id).toString();
					} else if (props.detail.sendTargetType == "4") {
						sendTarget.value.mobile = sendTarget.value.mobile.toString().replaceAll(",", ";");
						sendTarget.value.email = sendTarget.value.email.toString().replaceAll(",", ";");
						props.detail.sendTarget = sendTarget.value.email || sendTarget.value.mobile ? JSON.stringify(sendTarget.value) : "";
					}
					if (props.detail.sendTarget) {
						emit("submit");
					} else {
						ElMessage.error("请选择通知对象");
					}
				}
			});
		};
		const deptList = ref();
		onMounted(async () => {
			let res = await getDeptList();
			deptList.value = res.result.records.children;
			initTemplateList();
			if (props.detail.id) {
				if (props.detail.templateId) {
					let obj = JSON.parse(props.detail.templateId);
					//初始化通知模版选择
					templateSelectList.value = Object.keys(obj).map((item: any) => {
						return { id: obj[item], type: item };
					});
				}
				if (props.detail.sendTargetType == "3") {
					initUser();
				} else if (props.detail.sendTargetType == "4" && JSON.parse(props.detail.sendTarget)) {
					sendTarget.value.email =
						JSON.parse(props.detail.sendTarget).email && JSON.parse(props.detail.sendTarget).email.split(";");
					sendTarget.value.mobile =
						JSON.parse(props.detail.sendTarget).mobile && JSON.parse(props.detail.sendTarget).mobile.split(";");
				}
			} else {
				props.detail.status = "1";
				props.detail.sendTargetType = "1";
			}
		});
		//初始化消息模版
		const initTemplateList = async () => {
			let { result } = await getNotifyTemplateList({});
			result.map((item: any) => {
				if (item.type == "1") {
					options.value[0].options = [...options.value[0].options, item];
				} else if (item.type == "2") {
					options.value[1].options = [...options.value[1].options, item];
				}
			});
		};
		const initUser = async () => {
			let { result } = await getUserList({ id: props.detail.sendTarget as string });
			userSelect(result.records);
		};
		const options = ref<any>([
			{ label: "短信", options: [] },
			{ label: "邮件", options: [] }
		]);
		//转换通知模版选择的数据
		const templateIdChange = (val: any) => {
			let currentSelect = val[val.length - 1];
			if (currentSelect) {
				templateSelectList.value = val.filter((item: any) => {
					return (item.type == currentSelect.type && item.id == currentSelect.id) || item.type != currentSelect.type;
				});
				let obj: any = {};
				templateSelectList.value.map((item: any) => {
					obj[item.type] = item.id;
				});
				props.detail.templateId = JSON.stringify(obj);
			}
		};
		//通知对象按分组树选择数据处理
		const submitAssignGroup = (val: any) => {
			assignGroup.value = val.checked;
		};
		const assignGroup = ref([]);
		//选择的通知模版
		const templateSelectList = ref<any>([]);
		const sendTarget = ref({ mobile: "", email: "" });
		const userList = ref([]);
		const drawerVisible = ref(false);

		const userSelect = (val: any) => {
			userList.value = val;
			// userList.value = val.map((item: any) => {
			// 	return item.username;
			// });
		};
		return () => {
			return (
				<DialogBox {...attrs} onConfirm={validData} width="700px">
					<el-form model={props.detail} ref={formRef} rules={formRule} size="large" label-width="100">
						<el-form-item label="配置名称" prop="name">
							<el-input v-model={props.detail.name} />
						</el-form-item>
						<el-form-item label="分组" prop="deptId">
							<SelectDeptList detail={props.detail} />
						</el-form-item>
						<el-form-item label="状态" prop="status">
							<el-radio-group v-model={props.detail.status}>
								<el-radio label="1">启用</el-radio>
								<el-radio label="0">停用</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="通知模板" prop="templateId">
							<el-select
								v-model={templateSelectList.value}
								placeholder="请选择"
								multiple
								class="w-full"
								onChange={templateIdChange}
								value-key="id"
							>
								{options.value.map((group: any) => {
									return (
										<el-option-group key={group.label} label={group.label}>
											{group.options.map((item: any) => {
												return <el-option key={item.id} label={item.name} value={item}></el-option>;
											})}
										</el-option-group>
									);
								})}
							</el-select>
						</el-form-item>
						<el-form-item label="通知对象" prop="sendTargetType">
							<el-radio-group v-model={props.detail.sendTargetType}>
								<el-radio label="1">按分组</el-radio>
								<el-radio label="3">按人员</el-radio>
								<el-radio label="4">自定义</el-radio>
							</el-radio-group>
						</el-form-item>
						{props.detail.sendTargetType == "1" && (
							<DeptTree
								detail={{ deptId: props.detail.sendTarget && props.detail.sendTarget.split(",") }}
								multiple
								onChange={submitAssignGroup}
								class="ml-4"
							/>
						)}
						<UserSelectDialog
							v-model:visible={drawerVisible.value}
							onSubmit={userSelect}
							selectDefault={userList.value.map((item: any) => item.id)}
						></UserSelectDialog>
						{props.detail.sendTargetType == "3" && (
							<el-form-item label="人员">
								<el-select
									class="w-full "
									v-model={userList.value}
									placeholder="请选择人员"
									multiple
									value-key="id"
									onFocus={() => {
										drawerVisible.value = true;
									}}
								>
									{userList.value.map((item: any) => {
										return <el-option key={item.id} label={item.username} value={item}></el-option>;
									})}
								</el-select>
							</el-form-item>
						)}
						{props.detail.sendTargetType == "4" && (
							<div>
								<el-form-item label="邮件">
									<el-select
										v-model={sendTarget.value.email}
										placeholder="请输入邮件"
										multiple
										filterable
										allow-create
										default-first-option
										class="w-full"
									></el-select>
								</el-form-item>
								<el-form-item label="手机号">
									<el-select
										v-model={sendTarget.value.mobile}
										placeholder="请输入手机号"
										multiple
										filterable
										allow-create
										default-first-option
										class="w-full"
									></el-select>
								</el-form-item>
							</div>
						)}
					</el-form>
				</DialogBox>
			);
		};
	}
});
